package cn.tiansu.eway.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * 属性文件配置加载器
 * 
 * @author wupeng
 * 
 */
public class PropertyConfigurator
{
	private final static Logger log = Logger.getLogger(PropertyConfigurator.class);
	private Properties prop;
	private static Map<String, PropertyConfigurator> configMap = new HashMap<String, PropertyConfigurator>();

	/**
	 * 获取实例
	 * 
	 * @param clazz
	 *            配置文件路径
	 * @param configFile
	 *            配置文件
	 * @return
	 */
	public static PropertyConfigurator getInstance(Class clazz,
			String configFile)
	{
		PropertyConfigurator instance = null;
		if (configMap.get(configFile) == null)
		{
			instance = new PropertyConfigurator(clazz, configFile);
			configMap.put(configFile, instance);
		}
		else
		{
			instance = configMap.get(configFile);
		}
		return instance;
	}

	/**
	 * 加载文件
	 * 
	 * @param clazz
	 *            配置文件路径
	 * @param configFile
	 *            文件路径+文件名
	 */
	private PropertyConfigurator(Class clazz, String configFile)
	{
		FileInputStream is = null;
		try
		{
			is = new FileInputStream(System.getProperty("user.dir")+File.separator+"config"+File.separator+configFile);
		} catch (FileNotFoundException e)
		{
			log.error("", e);
		}
		try
		{
			prop = new Properties();
			prop.load(is);
		}
		catch (IOException ex)
		{
			log.error(configFile + "加载异常:" + ex.getMessage(), ex);
		}
	}

	/**
	 * 获取某项对应的值
	 * 
	 * @param name
	 *            配置文件参数名
	 * @return
	 */
	public String getParameter(String name)
	{
		String value = prop.getProperty(name);
		if (value != null)
		{
			try
			{
				// java读取properties文件 默认 ISO-8859-1，转为UTF-8
				value = new String(value.getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e)
			{
				log.error("UnsupportedEncoding is fail!",e);
			} 
			value = value.trim();
		}
		return value;
	}

	/**
	 * 获取全部参数
	 * 
	 * @return
	 */
	public Map<String, String> getAllParameters()
	{
		Map<String, String> paraMap = new HashMap<String, String>();
		Iterator<Map.Entry<Object, Object>> it = prop.entrySet().iterator();
		while (it.hasNext())
		{
			Map.Entry<Object, Object> entry = it.next();
			String key = String.valueOf(entry.getKey());
			String value = String.valueOf(entry.getValue());
			paraMap.put(key, value);
		}
		return paraMap;
	}
}
